package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.AutoCreateNumberUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dto.CustomerDto;
import com.ruoyi.system.domain.vo.ConsumerVo;
import com.ruoyi.system.service.CommonOpenApiService;
import com.ruoyi.system.service.OssUtil;
import com.ruoyi.system.wx.login.WxLoginService;
import com.ruoyi.system.wx.login.domain.WxLoginVo;
import com.ruoyi.system.wx.login.domain.WxUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.CustomerMapper;
import com.ruoyi.system.domain.Customer;
import com.ruoyi.system.service.ICustomerService;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import reactor.util.function.Tuple2;

import static com.ruoyi.common.constant.Constants.DEFAULT_CONSUMER_AVATOR;
import static com.ruoyi.common.constant.Constants.USER_NO_PREFIX;
import static com.ruoyi.common.utils.BizConsumerUtil.buildConsumerCache;
import static com.ruoyi.common.utils.BizConsumerUtil.getConsumerCache;
import static com.ruoyi.system.service.impl.CommonOpenApiServiceImpl.USER_USER_PREFIX;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-29
 */
@Service
public class CustomerServiceImpl implements ICustomerService {
    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private CommonOpenApiService commonOpenApiService;

    @Autowired
    private OssUtil ossUtil;


    @Value("${consumer.defaultAvator}")
    private String defaultAvator;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public Customer selectCustomerById(Long id) {
        return customerMapper.selectCustomerById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param customer 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<Customer> selectCustomerList(Customer customer) {
        return customerMapper.selectCustomerList(customer);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param customer 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertCustomer(Customer customer) {
        customer.setCreateTime(DateUtils.getNowDate());
        return customerMapper.insertCustomer(customer);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param customer 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateCustomer(Customer customer) {
        customer.setUpdateTime(DateUtils.getNowDate());
        return customerMapper.updateCustomer(customer);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteCustomerByIds(Long[] ids) {
        return customerMapper.deleteCustomerByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteCustomerById(Long id) {
        return customerMapper.deleteCustomerById(id);
    }

    @Override
    public int updateConsumerInfo(ConsumerVo consumerVo) {
        String phone = consumerVo.getPhone();
        String avatar = consumerVo.getTxdz();
        String platform = consumerVo.getPlatform();
        String username = consumerVo.getUsername();
        Assert.notNull(phone, "手机号为null");
        Customer consumer = customerMapper.selectConsumerByPhone(phone);
        if (Objects.nonNull(avatar)) {
            Assert.notNull(consumer, "客户未注册，请授权登录后再发起请求");
            consumer.setTxdz(avatar);
        }
        Assert.notNull(consumer, "未查询到当前客户");
        consumer.setPlatform(platform);
        consumer.setXm(username);
        return customerMapper.updateCustomer(consumer);
    }


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public CustomerDto getConsumerInfo(Long phone, String platform) {
        Customer cs = new Customer();
        cs.setSjh(phone);
        cs.setPlatform(platform);
        List<Customer> customers = customerMapper.selectCustomerList(cs);
        if (CollectionUtils.isEmpty(customers)) {
            throw new RuntimeException("未查询到用户信息");
        }
        CustomerDto customerDto = new CustomerDto();
        BeanUtil.copyProperties(customers.get(0), customerDto);
        return customerDto;
    }

    @Override
    public WxUserDto consumerLogin(WxLoginVo wxLoginVo) {

        String openId = commonOpenApiService.queryOpenId(wxLoginVo);

        Object userCache = redisTemplate.opsForHash().get(String.format(USER_USER_PREFIX, wxLoginVo.getPlatform()), openId);

        if (Objects.nonNull(userCache)) {
            String userCacheStr = userCache.toString();
            Tuple2<String, String> consumerCache = getConsumerCache(userCacheStr);
            return WxUserDto.builder().userType(commonOpenApiService.queryUserWorkType(openId)).openId(openId).phone(consumerCache.getT1()).consumerNo(consumerCache.getT2()).build();
        }

        String phoneNumber = commonOpenApiService.getPhoneNumber(wxLoginVo);

        Customer consumer = customerMapper.selectConsumerByPhone(phoneNumber);

        if (Objects.isNull(consumer)) {
            Customer customer = new Customer();
            customer.setCreateTime(new Date());
            customer.setUpdateTime(new Date());
            String consumerNo = AutoCreateNumberUtil.generateNo("", 6);
            String username = USER_NO_PREFIX + consumerNo;
            customer.setXm(username);
            customer.setPlatform(wxLoginVo.getPlatform());
            customer.setSjh(Long.parseLong(phoneNumber));
            customer.setConsumerNo(Long.parseLong(consumerNo));
            customer.setTxdz(defaultAvator);
            customerMapper.insertCustomer(customer);
            redisTemplate.opsForHash().put(String.format(USER_USER_PREFIX, wxLoginVo.getPlatform()), openId, buildConsumerCache(phoneNumber, consumerNo));
            return WxUserDto.builder().phone(phoneNumber).consumerNo(consumerNo).build();
        }

        redisTemplate.opsForHash().put(String.format(USER_USER_PREFIX, wxLoginVo.getPlatform()), openId, buildConsumerCache(phoneNumber, consumer.getConsumerNo().toString()));

        return WxUserDto.builder().userType(commonOpenApiService.queryUserWorkType(openId)).openId(openId).phone(phoneNumber).consumerNo(consumer.getConsumerNo().toString()).build();

    }


}
